const fs = require("fs-extra");
function Review(contents, username) {
    this.contents = contents;
    this.username = username;
}
function checkType(variable, type) {
    if (typeof type !== "string") throw "Type should be a string!";
    if (typeof variable !== type) throw `${variable} should be a type of ${type}`;
}
async function writeUserFile(path, username, data, type) {
    checkType(path, "string");
    checkType(username, "string");

    checkType(type, "string");

    try { 
        await fs.access(path); 
    } catch (e) {
        console.log(path + " does not exist! Create it Now!");
        await fs.writeFile(path, JSON.stringify({}));
    }
    let obj = await fs.readFile(path, "utf-8");
    obj = JSON.parse(obj);
    if (type === "password") {
        obj[username] = obj[username] || {};
        obj[username].password = data;
    } else if (type === "reviews") {
        obj[username].reviews = obj[username].reviews || [];
        obj[username].reviews.push(data);
    } else {
        throw "This type of data is not allowed to write into this kind of file!";
    }
    await fs.writeFile(path, JSON.stringify(obj));
}

/**
 * 
 * @param {string} path 
 * @return {Promise(object)} 
 */
async function readUserFile(path) {
    checkType(path, "string");
    let res;
    try {
       res = await fs.readFile(path, "utf-8");
    } catch (e) {
        return null;
    }
    return JSON.parse(res);
}

async function writeReviewFile(path, username, data) {
    try {
        await fs.access(path);
    } catch(e) {
        console.log(path + " does not exist! Creat it now!");
        await fs.writeFile(path, JSON.stringify([]));
    }
    let obj = await fs.readFile(path, "utf-8");
    obj = JSON.parse(obj);
    obj.push(new Review(data, username));
    await fs.writeFile(path, JSON.stringify(obj));
}

/**
 * 
 * @param {string} path 
 * @return {Promise(Array)}
 */
async function readReviewFile(path) {
    let res;
    try {
        res = await fs.readFile(path, "utf-8");
        return JSON.parse(res);
    } catch (e) {
        return [];
    }
}

module.exports = {
    writeUserFile,
    writeReviewFile,
    readUserFile,
    readReviewFile
};